from numpy import asarray as _asarray
from PIL.Image import open as _open
from wordcloud import WordCloud as _WordCloud
from jieba.posseg import cut as _cut


def freqDict(lst: list) -> dict:
    """按频率把列表转换成词典"""
    word_f = {}
    for w in lst:
        word_f[w] = word_f.get(w, 0)+1
    return word_f


def dictSort(d: dict, slot: int = 1, down: bool = True) -> list:
    """按频率对字典元素排序，默认降序"""
    return sorted(d.items(), key=lambda x: x[slot], reverse=down)


def genCloud(lst):
    """生成词云"""
    sw = set('的')
    n = len(lst)//50
    image = _asarray(_open("logo.jpg"))
    font = "SourceHanSansSC-Regular.otf"
    gen = _WordCloud(mask=image,
                     stopwords=sw,  # 停止词
                     max_words=n,  # 最大词数量
                     # relative_scaling=1,
                     prefer_horizontal=1,  # 文字水平放置
                     mode='RGBA',  # 颜色模式
                     font_path=font,  # 字体
                     font_step=4,
                     # background_color=None,#背景颜色
                     scale=1,  # 缩放规模
                     # width=400, height=200,
                     min_font_size=4, max_font_size=100,
                     random_state=20,
                     collocations=False,  # 不重复
                     )
    return gen.generate(lst)


def wordFrequency(word: str) -> dict:
    """分词并转换成频率词典"""
    content = _cut(word)
    dict_words = {}
    for w, flag in content:
        if flag in ['n', "nr", "ns"] and len(w) > 1:
            dict_words[w] = dict_words.get(w, 0)+1
    return dict_words


def showFreq(lst: list, num: int):
    """展示lst中频率前num个的词"""
    num = min(num, len(lst))
    total = sum(y for _, y in lst)
    print(f"{'序号':4}\t{'词语':4}\t{'频率':4}\t{'占比':4}")
    for i in range(num):
        print(f"{i:4}\t{lst[i][0]:4}\t{lst[i][1]:4}\t{lst[i][1]/total:.2%}")
